import React, { Component } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { Form, Input, Button, Icon, Alert } from 'antd';
import md5 from 'md5';
import styles from './Login.less';

const FormItem = Form.Item;

@connect(s => s.user)
@Form.create()
export default class Login extends Component {
  componentWillReceiveProps(nextProps) {
    if (nextProps.login.status === 'ok') {
      this.props.dispatch(routerRedux.push('/'));
    }
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  handleSubmit = (e) => {
    e.preventDefault();

    this.props.form.validateFields({ force: true },
      (err, values) => {
        if (!err) {
          const payload = { ...values, Passwd: md5(values.Passwd) };
          this.props.dispatch({ type: 'user/login', payload });
        }
      }
    );
  }

  renderMessage = (message) => {
    return (
      <Alert
        style={{ marginBottom: 24 }}
        message={message}
        type="error"
        showIcon
      />
    );
  }

  render() {
    const { form, login } = this.props;
    const { getFieldDecorator } = form;

    return (
      <div className={styles.main}>
        <Form onSubmit={this.handleSubmit}>
          {
            login.status &&
            login.status !== 'ok' &&
            login.submitting === false &&
            this.renderMessage(login.status)
          }
          <FormItem>
            {getFieldDecorator('Phone', {
              rules: [{
                required: true, message: '请输入手机号！',
              }],
            })(
              <Input
                size="large"
                prefix={<Icon type="user" className={styles.prefixIcon} />}
                placeholder="请输入手机号"
              />
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('Passwd', {
              rules: [{
                required: true, message: '请输入密码！',
              }],
            })(
              <Input
                size="large"
                prefix={<Icon type="lock" className={styles.prefixIcon} />}
                type="password"
                placeholder="请输入您的密码"
              />
            )}
          </FormItem>
          <FormItem className={styles.additional}>
            <Button size="large" loading={login.submitting} className={styles.submit} type="primary" htmlType="submit">
              登录
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}
